package com.aletto.general_store.ui.activities;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.InputFilter;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

import com.aletto.general_store.R;
import com.aletto.general_store.data.DataRepository;
import com.aletto.general_store.data.model.AuctionGoods;
import com.aletto.general_store.data.model.Response;
import com.aletto.general_store.data.model.Upload;
import com.aletto.general_store.presenters.AddGoodsTask;
import com.aletto.general_store.presenters.UpdateGoodsTask;
import com.aletto.general_store.presenters.core.SimpleTemplate;
import com.aletto.general_store.presenters.views.ProgressView;
import com.aletto.general_store.utils.DecimalDigitsInputFilter;
import com.aletto.general_store.utils.ToastUtils;
import com.aletto.general_store.utils.XHelper;
import com.aletto.general_store.utils.event.AddGoodsEvent;
import com.aletto.general_store.utils.image.AddImageLayout;
import com.aletto.general_store.utils.image.GlideEngine;
import com.aletto.general_store.utils.image.OnAddClickListener;
import com.aletto.general_store.utils.watchers.ContentObserver;
import com.aletto.general_store.utils.watchers.ContentSubject;
import com.aletto.general_store.utils.watchers.EmptyRule;
import com.aletto.general_store.utils.watchers.RecyclerViewObserver;
import com.luck.picture.lib.basic.PictureSelector;
import com.luck.picture.lib.config.SelectMimeType;
import com.luck.picture.lib.engine.CompressFileEngine;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.interfaces.OnKeyValueResultCallbackListener;
import com.luck.picture.lib.interfaces.OnResultCallbackListener;
import com.sisyphus.spinach.core.INetTask;
import com.sisyphus.spinach.network.presenters.NetSingleTask;


import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

import io.reactivex.rxjava3.core.Observable;
import io.reactivex.rxjava3.core.ObservableSource;
import io.reactivex.rxjava3.functions.Function;

import top.zibin.luban.Luban;
import top.zibin.luban.OnNewCompressListener;


/**
 * 商品发布
 */
public class ShelvesHitGoodsActivity extends AppCompatActivity {

    public static Intent newIntent(Context context, AuctionGoods item) {
        Intent intent = new Intent(context, ShelvesHitGoodsActivity.class);
        intent.putExtra(AuctionGoods.EXTRA_NAME, item);
        return intent;
    }

    public static Intent newIntent(Context context, int type) {
        Intent intent = new Intent(context, ShelvesHitGoodsActivity.class);
        intent.putExtra("TYPE", type); // 数据商品或实物商品
        return intent;
    }

    private String goodsId;
    private View buttonPublish;

    private TextView tv_main_image_limit;
    private AddImageLayout addImageView, add_desc_image_view;
    private EditText edit_title, edit_label, edit_price, edit_number;

    private List<LocalMedia> result1 = new ArrayList<>(), result2 = new ArrayList<>();

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_shelves_hit_goods);
        XHelper.initTitle(this, R.string.shelves_hit_goods);

        edit_title = findViewById(R.id.edit_title);
        edit_label = findViewById(R.id.edit_label);
        edit_price = findViewById(R.id.edit_price);
        edit_number = findViewById(R.id.edit_number);
        tv_main_image_limit = findViewById(R.id.tv_main_image_limit);
        addImageView = findViewById(R.id.add_image_view);
        add_desc_image_view = findViewById(R.id.add_desc_image_view);
        buttonPublish = findViewById(R.id.button_publish);

        Intent intent = getIntent();
        int goodsType = intent.getIntExtra("TYPE", 1);

        initAddCover();

        initAddDescImage();

        buttonPublish.setOnClickListener(v -> addGoods(goodsType).execute());

        initEnabled();

//        edit_price.setFilters(new InputFilter[]{new DecimalDigitsInputFilter(2)});
        edit_price.addTextChangedListener(new DecimalDigitsInputFilter(2));

        // 预览
        findViewById(R.id.tv_preview).setOnClickListener(v -> preview());

        // 编辑
        AuctionGoods item = (AuctionGoods) intent.getSerializableExtra(AuctionGoods.EXTRA_NAME);
        if (item != null) {
            goodsId = item.getId();
            edit_title.setText(item.getName());
            edit_label.setText(String.join(",", item.getLabel()));
            edit_price.setText(item.getPrice());
            edit_number.setText(String.valueOf(item.getTotal_stock()));
            addImageView.addPath(item.getGoods_img()); // 封面
            add_desc_image_view.addPath(item.getDesc()); // 介绍

            tv_main_image_limit.setText(String.format(getString(R.string.shelves_hit_main_image), item.getGoods_img().size()));
        }
    }

    private void initEnabled() {
        addImageView.setOnAddClickListener(new OnAddClickListener() {
            @Override
            public void add() {

            }

            @Override
            public void delete(int position, View view) {
                tv_main_image_limit.setText(String.format(getString(R.string.shelves_hit_main_image), addImageView.obtainData().size()));
            }
        });

//        ContentObserver addImageViewObserver = new ContentObserver();
//        ContentObserver addDescImageViewObserver = new ContentObserver();
        RecyclerViewObserver addImageViewObserver = new RecyclerViewObserver();
        RecyclerViewObserver addDescImageViewObserver = new RecyclerViewObserver();

        addImageView.registerAdapterDataObserver(addImageViewObserver);
        add_desc_image_view.registerAdapterDataObserver(addDescImageViewObserver);

        ContentSubject contentSubject = new ContentSubject();
        contentSubject
                .add(edit_title, new EmptyRule(edit_title))
                .add(edit_price, new EmptyRule(edit_price))
                .add(edit_number, new EmptyRule(edit_number))
                .add(addImageViewObserver, () -> !addImageView.obtainData().isEmpty())
                .add(addDescImageViewObserver, () -> !add_desc_image_view.obtainData().isEmpty())
                .setOnEnableListener(buttonPublish::setEnabled);
    }

    private void preview() {
        if (TextUtils.isEmpty(edit_title.getText()) || TextUtils.isEmpty(edit_price.getText())) {
            ToastUtils.makeText(R.string.tips_preview_title);
            return;
        }

        if (addImageView.getItemCount() < 1 || add_desc_image_view.getItemCount() < 1) {
            ToastUtils.makeText(R.string.tips_preview_image);
            return;
        }

        // 跳转预览
        startActivity(PreviewGoodsActivity.newIntent(
                        this,
                        edit_title.getText(),
                        edit_price.getText(),
                        new ArrayList<>(addImageView.obtainData()),
                        new ArrayList<>(add_desc_image_view.obtainData())
                )
        );
    }

    private SimpleTemplate<Object> addGoods(int goodsType) {
        String name = edit_title.getText().toString();
        String label = edit_label.getText().toString();
        String price = edit_price.getText().toString();
        int number = Integer.parseInt(edit_number.getText().toString());

        if (goodsId == null) { // 添加商品
            return new AddGoodsTask(this, name, label, price, number, goodsType, addImageView.obtainData(), add_desc_image_view.obtainData());
        }

        // 修改商品
        return new UpdateGoodsTask(this, number, goodsType, goodsId, name, label, price, addImageView.obtainData(), add_desc_image_view.obtainData());
    }

    private void initAddCover() {
        tv_main_image_limit.setText(String.format(getString(R.string.shelves_hit_main_image), 0));

        addImageView.setOnAddClickListener(() -> {

            ArrayList<LocalMedia> result = new ArrayList<>();
            if (result1 != null) {
                for (LocalMedia localMedia : result1) {
                    List<String> paths = addImageView.obtainData();
                    for (String path : paths) {
                        if (localMedia.getRealPath().equals(path)) {
                            result.add(localMedia);
                            break;
                        }
                    }
                }
            }

            PictureSelector.create(ShelvesHitGoodsActivity.this)
                    .openGallery(SelectMimeType.ofImage())
                    .isDisplayCamera(false)
                    .setSelectedData(result)
                    .setMaxSelectNum(5)
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setCompressEngine(new CompressFileEngine() {
                        @Override
                        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
                            Luban.with(context).load(source).ignoreBy(100)
                                    .setCompressListener(new OnNewCompressListener() {
                                        @Override
                                        public void onStart() {

                                        }

                                        @Override
                                        public void onSuccess(String source, File compressFile) {
                                            if (call != null) {
                                                call.onCallback(source, compressFile.getAbsolutePath());
                                            }
                                        }

                                        @Override
                                        public void onError(String source, Throwable e) {
                                            if (call != null) {
                                                call.onCallback(source, null);
                                            }
                                        }
                                    }).launch();
                        }

                    })
                    .forResult(new OnResultCallbackListener<>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            result1 = result;

                            if (result.size() > 1) {
                                addImageView.addPath(
                                        result.stream()
                                                .map(LocalMedia::getRealPath)
                                                .collect(Collectors.toList())
                                );

                            } else {
                                addImageView.add(result.get(0).getRealPath());
                            }

                            tv_main_image_limit.setText(
                                    String.format(getString(R.string.shelves_hit_main_image),
                                            addImageView.getItemCount())
                            );

                        }

                        @Override
                        public void onCancel() {

                        }

                    });
        });
    }

    private void initAddDescImage() {
        add_desc_image_view.setOnAddClickListener(() -> {

            ArrayList<LocalMedia> result = new ArrayList<>();
            if (result2 != null) {
                for (LocalMedia localMedia : result2) {
                    List<String> paths = add_desc_image_view.obtainData();
                    for (String path : paths) {
                        if (localMedia.getRealPath().equals(path)) {
                            result.add(localMedia);
                            break;
                        }
                    }
                }
            }

            PictureSelector.create(ShelvesHitGoodsActivity.this)
                    .openGallery(SelectMimeType.ofImage())
                    .isDisplayCamera(false)
                    .setSelectedData(result)
                    .setMaxSelectNum(10)
                    .setImageEngine(GlideEngine.createGlideEngine())
                    .setCompressEngine(new CompressFileEngine() {
                        @Override
                        public void onStartCompress(Context context, ArrayList<Uri> source, OnKeyValueResultCallbackListener call) {
                            Luban.with(context).load(source).ignoreBy(100)
                                    .setCompressListener(new OnNewCompressListener() {
                                        @Override
                                        public void onStart() {

                                        }

                                        @Override
                                        public void onSuccess(String source, File compressFile) {
                                            if (call != null) {
                                                call.onCallback(source, compressFile.getAbsolutePath());
                                            }
                                        }

                                        @Override
                                        public void onError(String source, Throwable e) {
                                            if (call != null) {
                                                call.onCallback(source, null);
                                            }
                                        }
                                    }).launch();
                        }

                    })
                    .forResult(new OnResultCallbackListener<>() {
                        @Override
                        public void onResult(ArrayList<LocalMedia> result) {
                            result2 = result;
                            if (result.size() > 1) {
                                add_desc_image_view.addPath(
                                        result.stream()
                                                .map(LocalMedia::getRealPath)
                                                .collect(Collectors.toList())
                                );

                            } else {
                                add_desc_image_view.add(result.get(0).getRealPath());
                            }
                        }

                        @Override
                        public void onCancel() {

                        }

                    });
        });
    }

}
